<template>
  <div class="c2cTrade">
    <Other-Header index="1" bgColor="#5741d9"></Other-Header>
    <div class="releaseAd mainSection clearfix">
      <div class="releaseAdBox leftBox fl">
        <div class="inner">
          <h3 class="title">{{$t('l.advert_about0')}}</h3>
          <div class="formBox">
            <el-form
              label-position="top"
              ref="advertForm"
              :rules="rules"
              label-width="80px"
              :model="advertForm"
            >
              <el-row :gutter="22">
                <el-col :span="12">
                  <el-form-item :label="$t('l.advert_about1')">
                    <el-select v-model="advertForm.type">
                      <el-option
                        v-for="(item,index) in advertType"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item :label="$t('l.advert_about5')">
                    <el-select v-model="advertForm.legalCurrencyCode">
                      <el-option
                        v-for="(item, index) in legalCurrency"
                        :key="index"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :span="12">
                  <el-form-item :label="$t('l.advert_about4')">
                    <el-select v-model="advertForm.currencyCode" @change="getAvailableQuantity">
                      <el-option
                        v-for="(item,index) in currencyCode"
                        :key="index"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item :label="$t('l.advert_about6')" prop="price">
                <el-input
                  :placeholder="`${$t('l.advert_about8')}${proposedPrice}`"
                  v-model="advertForm.price"
                >
                  <i slot="suffix" class="el-input__text">{{advertForm.legalCurrencyCode}}</i>
                </el-input>
              </el-form-item>
              <el-form-item prop="totalQuantity">
                <span slot="label">
                  {{$t('l.advert_about9')}}
                  <em
                    class="el-text-blue"
                    v-show="advertForm.type==2"
                  >{{$t('l.advert_about11')}}：{{availableAmount}}{{advertForm.currencyCode}}</em>
                </span>
                <el-input
                  :placeholder="$t('l.advert_about10')"
                  v-model.number="advertForm.totalQuantity"
                >
                  <i
                    slot="suffix"
                    class="el-input__text"
                    style="margin-right: 10px;"
                  >{{advertForm.currencyCode}}</i>
                  <i
                    slot="suffix"
                    class="el-input__text el-suffix-icon"
                    @click="advertForm.totalQuantity=Number(availableAmount)"
                    v-show="advertForm.type==2"
                  >{{$t('l.advert_about12')}}</i>
                </el-input>
              </el-form-item>
              <el-form-item :label="$t('l.advert_about13')" prop="limit">
                <el-col :span="10">
                  <el-input :placeholder="$t('l.advert_about14')" v-model="advertForm.limit.min"></el-input>
                </el-col>
                <el-col :span="2" style="text-align: center;">
                  <span class="line"></span>
                </el-col>
                <el-col :span="10">
                  <el-input :placeholder="$t('l.advert_about15')" v-model="advertForm.limit.max"></el-input>
                </el-col>
                <el-col
                  :span="2"
                  style="text-align: right;"
                >{{advertForm.type==1 ? advertForm.currencyCode:advertForm.legalCurrencyCode}}</el-col>
              </el-form-item>
              <el-form-item :label="$t('l.advert_about16')">
                <el-input
                  type="textarea"
                  v-model="advertForm.remark"
                  :placeholder="$t('l.advert_about17')"
                ></el-input>
              </el-form-item>
              <el-form-item :label="$t('l.advert_about18')" prop="payModes">
                <div class="fr" style="padding-top: 10px;">
                  <router-link to="/paymenttype" class="el-text-blue">{{$t('l.advert_about22a')}}</router-link>
                  {{$t('l.advert_about22b')}}
                </div>
                <el-checkbox-group v-model="advertForm.payModes" style="padding-top: 10px;">
                  <el-checkbox
                    v-for="item in userPayMode"
                    :key="item.id"
                    :label="item.value"
                    :disabled="!item.enable"
                    border
                  >{{item.label}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <div class="btnBox">
                <el-button
                  type="primary"
                  class="btn-apply"
                  @click="onSubmit"
                >{{$t('l.advert_about23')}}</el-button>
              </div>
            </el-form>
          </div>
        </div>
      </div>
      <!-- 交易须知 -->
      <div class="rightBox fr">
        <Instructions></Instructions>
      </div>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import { api } from "@/api/api";
import OtherHeader from "@/components/otherHeader";
import Footer from "@/components/footer";
import Instructions from "@/components/instructions";
import { constants } from "fs";

export default {
  components: {
    OtherHeader,
    Footer,
    Instructions
  },
  data() {
    var validatePositiveNumber = (rule, value, callback) => {
      setTimeout(() => {
        if (value <= 0) {
          callback(new Error(this.$t("l.form_validate0")));
        } else {
          callback();
        }
      }, 500);
    };
    var validateLimit = (rule, value, callback) => {
      let reg = /^[0-9]*$/;
      if (!value) {
        callback(
          new Error(
            rule.field == "min"
              ? this.$t("l.form_validate1")
              : this.$t("l.form_validate2")
          )
        );
      }
      if (!reg.test(value)) {
        callback(new Error(this.$t("l.form_validate3")));
      }
      setTimeout(() => {
        if (value <= 0) {
          callback(new Error(this.$t("l.form_validate0")));
        } else {
          callback();
        }
      }, 500);
    };
    return {
      isLogin: this.$store.state.usertoken ? true : false,
      payModes: [],
      enablePayModes: [],
      currencyCode: [],
      legalCurrency: [],
      advertType: [
        {
          label: this.$t("l.advert_about3"),
          value: 1
        },
        {
          label: this.$t("l.advert_about2"),
          value: 2
        }
      ],
      prices: [], // 参考价格
      availableAmount: 0, // 可用余额
      advertForm: {
        type: 1, // 广告类型
        legalCurrencyCode: "CNY", // 法币类型
        currencyCode: "USDT", //币种
        price: "", // 单价
        totalQuantity: "", // 数量
        limit: {
          min: "", // 单笔限额最小值
          max: "" // 单笔限额最大值
        },
        remark: "", // 备注
        payModes: [] // 收付款方式
      },
      rules: {
        currencyCode: [
          {
            required: true,
            message: this.$t("l.form_validate4"),
            trigger: "blur"
          }
        ],
        legalCurrencyCode: [
          {
            required: true,
            message: this.$t("l.form_validate5"),
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: this.$t("l.form_validate6"),
            trigger: "blur"
          },
          // {
          //   type: "number",
          //   message: this.$t("l.form_validate3"),
          //   trigger: "blur"
          // },
          { validator: validatePositiveNumber, trigger: "blur" }
        ],
        totalQuantity: [
          {
            required: true,
            message: this.$t("l.form_validate7"),
            trigger: "blur"
          },
          {
            type: "number",
            message: this.$t("l.form_validate3"),
            trigger: "blur"
          },
          { validator: validatePositiveNumber, trigger: "blur" }
        ],
        payModes: [
          {
            required: true,
            message: this.$t("l.form_validate8"),
            trigger: "blur"
          }
        ],
        limit: [
          {
            type: "object",
            required: true,
            trigger: "blur",
            fields: {
              min: {
                required: true,
                validator: validateLimit,
                trigger: "blur"
              },
              max: {
                required: true,
                validator: validateLimit,
                trigger: "blur"
              }
            }
          }
        ]
      }
    };
  },
  computed: {
    proposedPrice() {
      let priceObj = this.prices.find(
        value => value.symbol == this.advertForm.legalCurrencyCode
      );

      return priceObj && priceObj.price;
    },
    userPayMode() {
      if (!this.payModes.length) return [];

      return this.payModes.map(item => ({
        ...item,
        enable: this.enablePayModes.indexOf(Number(item.value)) != -1
      }));
    }
  },
  async created() {
    this.init();
  },
  methods: {
    init() {
      this.getProposedPrice();
      this.getUserEnablePayMode();
      this.getUserAllPayMode();
      this.getCurrency();
      this.getLegalCurrency();
      this.getAvailableQuantity();
    },
    // 币种可用余额
    async getAvailableQuantity() {
      let res = await api.findByCurrencyCode({
        currencyCode: this.advertForm.currencyCode
      });
      let { code, data, msg } = res.data;
      if (code == 0) {
        this.availableAmount = Number(data.availableAmount);
      }
    },
    // 获取参考价
    async getProposedPrice() {
      let res = await api.getProposedPrice();
      let { code, data, msg } = res.data;

      if (code == 0) {
        this.prices = Object.assign([], data);
      }
    },
    // 获取用户已启用的支付方式
    async getUserEnablePayMode() {
      let res = await api.userPayMode();
      let { code, data, msg } = res.data;

      if (code == 0) {
        this.enablePayModes = data.map(item => item.accountType);
      } else {
        this.$layer.msg(msg);
      }
    },
    // 获取用户可用支付方式
    async getUserAllPayMode() {
      let res = await api.selectList({
        language: "zh_CN",
        category: "PAY_MODES"
      });
      let { code, data: items, msg } = res.data;

      if (code == 0) {
        this.payModes = items.map(item => ({
          label: item.name,
          value: item.value
        }));
      } else {
        this.$layer.msg(msg);
      }
    },
    // 币种列表
    async getCurrency() {
      let res = await api.currency();
      let { code, data: items } = res.data;

      if (code == 0) {
        items.forEach(item => {
          this.currencyCode.push(item);
        });
      }
    },
    // 法币类型
    async getLegalCurrency() {
      let res = await api.selectList({
        language: "zh_CN",
        category: "FIAT"
      });
      let { code, data: items, msg } = res.data;

      if (code == 0) {
        this.legalCurrency = items.map(item => item.value);
      } else {
        this.$layer.msg(msg);
      }
    },
    //获取一次性token
    async createOnceToken() {
      let res = await api.createOnceToken();
      if (res.data.code == 0) {
        return res.data.data.resultToken;
      }
    },
    onSubmit() {
      if (!this.isLogin) {
        this.$router.push("/login");
        return false;
      }

      this.$refs["advertForm"].validate(valid => {
        if (valid) {
          this.publishAdvert();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async publishAdvert() {
      let payModes = "";
      this.advertForm.payModes.forEach(function(item, index) {
        if (index == 0) {
          payModes += item;
        } else {
          payModes += "," + item;
        }
      });
      let param = {
        type: this.advertForm.type,
        currencyCode: this.advertForm.currencyCode,
        legalCurrencyCode: this.advertForm.legalCurrencyCode,
        price: this.advertForm.price,
        totalQuantity: this.advertForm.totalQuantity,
        limitMin: this.advertForm.limit.min,
        limitMax: this.advertForm.limit.max,
        remark: this.advertForm.remark,
        payModes: payModes,
        onceToken: await this.createOnceToken()
      };

      let res = await api.createAdvert(param);

      if (res.data.code == 0) {
        this.$layer.msg(res.data.msg);
        this.$router.push("/myAdvert");
      } else {
        this.$layer.msg(res.data.msg);
      }
    }
  },
  mounted() {
    this.createOnceToken();
  }
};
</script>

<style lang="less" scoped>
.c2cTrade {
  background-color: #f7f8fc;
  position: absolute;
  min-height: 100%;
  width: 100%;
  padding-top: 100px;
}
.releaseAd {
  width: 1200px;
  margin: 20px auto 0;
  height: 990px;
  box-sizing: border-box;
  padding-bottom: 160px;
  .leftBox {
    width: 850px;
    height: 830px;
    box-sizing: border-box;
    padding: 36px 143px;
    background: #fff;
  }
  .rightBox {
    width: 334px;
    height: 830px;
    padding: 32px 32px 27px;
    background: #fff;
    box-sizing: border-box;
  }
  .inner {
    background-color: #fff;
    height: 100%;
    box-sizing: border-box;

    > .title {
      font-size: 18px;
      font-weight: 600;
      color: rgba(51, 56, 94, 1);
      line-height: 100%;
      border-left: 3px solid #2D8DFE;
      padding-left: 10px;
      margin-left: -100px;
      margin-bottom: 36px;
    }
  }
}

/deep/.formBox {
  width: 564px;
  margin: 0 auto;
  .btnBox {
    padding-top: 20px;
  }
  .line {
    display: inline-block;
    width: 23px;
    height: 1px;
    background: #e9eef4;
  }
  .btn-apply {
    width: 100%;
    height: 40px;
    background: linear-gradient(90deg,#3360FF 0%,#04A6FE 100%);
    color: #fff;
    border-radius: 4px;
  }
  .noteTip {
    height: 20px;
    font-size: 14px;
    font-familyA: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(239, 87, 86, 1);
    line-height: 20px;
    text-align: center;
    margin-top: 14px;
  }
  .el-form-item.is-required .el-form-item__label:before {
    display: none;
  }
  .el-form-item__label {
    height: 20px;
    font-size: 14px;
    font-familyA: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 56, 94, 1);
    line-height: 20px;
    margin-bottom: 5px;
    em {
      position: absolute;
      top: 0;
      right: 0;
      // opacity: 0.5;
      font-style: normal;
    }
  }
  .el-input__suffix {
    right: 11px;
  }
  .el-form-item {
    position: relative;
    margin-bottom: 22px;
  }
  .el-input__inner {
    font-size: 14px;
    color: #33385e;
  }
  .el-input__text {
    font-style: normal;
    color: #33385e;
  }
  .el-text-blue {
    color: #2D8DFE;
    cursor: pointer;
  }
  .el-suffix-icon {
    display: inline-block;
    width: 50px;
    height: 26px;
    line-height: 26px;
    background: rgba(249, 249, 255, 1);
    border-radius: 2px;
    border: 1px solid rgba(233, 238, 244, 1);
    font-size: 14px;
    cursor: pointer;
  }
  .el-input.is-disabled .el-input__inner {
    color: #33385e;
  }
  .el-textarea__inner {
    height: 77px;
  }
  .el-checkbox {
    width: 109px;
    height: 44px;
    line-height: 44px;
    padding: 0;
    color: #33385e;
    text-align: center;
    background: #f2f6fa;
    border-width: 0;
    box-sizing: border-box;
    &.is-checked {
      background: url(../../assets/images/pay-selected.png) no-repeat center top;
    }
  }
  .el-checkbox__label {
    padding-left: 0;
  }
  .el-checkbox__input {
    display: none;
  }
  .el-select {
    width: 100%;
  }
}
</style>